from argparse import ArgumentParser
from datafeed import BinanceSpotFeed
from pymongo import MongoClient
import logging
import sys

logging.basicConfig(
    stream=sys.stdout, level=logging.INFO, format="%(asctime)s-%(levelname)s-%(message)s"
)


class Worker(object):
    def __init__(self, url):
        self.client = MongoClient(url)
        self.datafeed = BinanceSpotFeed(self.on_message)

    def on_replace(self, symbol, tick):
        resp = self.client.BinanceSpotMinute[symbol].replace_one({"datetime": tick["datetime"]}, tick, upsert=True)
        return resp.raw_result

    def on_message(self, msg):
        resp = self.on_replace(msg['symbol'], {
            "datetime": msg["datetime"],
            "open": msg["open"], "high": msg["high"], "low": msg["low"], "close": msg["close"],
            "volume": msg["volume"], "amount": msg["amount"]
        })
        logging.info(f"OnUpdates: Symbol-{msg['symbol']}, {resp}")

    def start(self):
        self.datafeed.start()


def main():
    parser = ArgumentParser()
    parser.add_argument("--url", type=str, help="mongodb://{username}:{password}@{host}:{port}/admin?authSource=admin")
    params = parser.parse_args()
    Worker(params.url).start()


if __name__ == "__main__":
    main()
